const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const jwt = require('jsonwebtoken')
const SECRET = 'asdfta219*&%^jWJSHFJ'


router.post('/deleteEmployee', async (req, res) => {
    console.log(req.body)
    //token
    const result = jwt.verify(req.body.token, SECRET)
    let sql = 'select departmentId from user_role where username = ?'
    db.base(sql, result.username, response_temp => {
        if(response_temp!=null&&response_temp.length==1){
            console.log(response_temp)
            sql = 'select workNumber from department_employees WHERE departmentId = ?'
            db.base(sql,response_temp[0].departmentId,response_temp=>{
                console.log(response_temp)
                flag = false
                for (let i = 0; i < response_temp.length; i++) {
                    if(req.body.workNumber == response_temp[i].workNumber){
                        flag = true
                    }
                }
                console.log(flag)
                if(flag){
                    sql = 'DELETE FROM employees WHERE work_number = ?'
                    db.base(sql,req.body.workNumber,response_temp=>{
                        console.log(response_temp)
                        if(response_temp!= null && response_temp.affectedRows == 1){
                            res.json({
                                result:"success"
                            })
                        }else{
                            res.json({
                                result:"error"
                            })
                        }
                    })
                }else{
                    res.json({
                        result:"error"
                    })
                }
            })
        }else{
            res.json({
                result:"error"
            })
        }
    })
})

module.exports = router
